<?php

# shield PHP warning and error prompt
# ini_set("display_errors", "Off");

function output($obj) {
  echo json_encode($obj, JSON_UNESCAPED_UNICODE);
}

function is_json($string) {
  json_decode($string);
  return (json_last_error() == JSON_ERROR_NONE);
}

function json_stringify($obj) {
  return json_encode($obj, JSON_UNESCAPED_UNICODE);
}

function json_parse($json = '', $assoc = true) {
  $object = json_decode($json, $assoc);
  $error = json_last_error();
  if ($error == JSON_ERROR_NONE) {
    return $object;
  } else {
    return $json;
  }
}

function query_parse($data = [], $assoc = true) {
  $data_new = [];
  foreach ($data as $row => $line) {
    foreach ($line as $col => $cell) {
      $data_new[$row][$col] = json_parse($cell, $assoc);
    }
  }
  return $data_new;
}

function timestamp() {
  $mill_time = microtime();
  $timeInfo = explode(' ', $mill_time);
  $milis_time = sprintf('%d%03d', $timeInfo[1], $timeInfo[0] * 1000);
  return (int)$milis_time;
}

function get_client_ip() {
  if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
    $ip = getenv("HTTP_CLIENT_IP");
  } elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
    $ip = getenv("HTTP_X_FORWARDED_FOR");
  } elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
    $ip = getenv("REMOTE_ADDR");
  } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
    $ip = $_SERVER['REMOTE_ADDR'];
  } else {
    $ip = "unknown";
  }
  return $ip;
}
